#coding=utf-8
import base64
import datetime
import json
import random
import urllib

from flask import request, url_for, make_response
from flask_appbuilder import BaseView, expose, has_access
from werkzeug.utils import redirect, secure_filename

from app import appbuilder, db, socketio, app
import os, re


class ZTreeSampleView(BaseView):
    route_base = '/ztree'
    CONFIG = None

    def __init__(self):
        super(ZTreeSampleView, self).__init__()


    @expose('/', methods=('GET','POST'))
    def index(self):
        return self.render_template('ztree/index.html')

    @expose("/drag_super")
    def drag_super(self):
        return self.render_template('ztree/drag_super.html')

    @expose("/edit_super")
    def edit_super(self):
        return self.render_template('ztree/edit_super.html')

    def upload_image(self):
        fieldName = self.CONFIG.get('imageFieldName')
        config = {
            "pathFormat": self.CONFIG['imagePathFormat'],
            "maxSize": self.CONFIG['imageMaxSize'],
            "allowFiles": self.CONFIG['imageAllowFiles']
        }
        return self.save(fieldName, config)

    def upload_video(self):
        fieldName = self.CONFIG.get('videoFieldName')
        config = {
            "pathFormat": self.CONFIG['videoPathFormat'],
            "maxSize": self.CONFIG['videoMaxSize'],
            "allowFiles": self.CONFIG['videoAllowFiles']
        }
        return self.save(fieldName, config)

    def upload_file(self):
        fieldName = self.CONFIG.get('fileFieldName')
        config = {
            "pathFormat": self.CONFIG['filePathFormat'],
            "maxSize": self.CONFIG['fileMaxSize'],
            "allowFiles": self.CONFIG['fileAllowFiles']
        }
        return self.save(fieldName, config)

    def save(self, fieldName, config):
        if fieldName in request.files:
            field = request.files[fieldName]
            uploader = Uploader(field, config, app.static_folder)
            return uploader.getFileInfo()
        else:
            return dict(state='上传接口出错')

    def upload_scrawl(self):
        # 涂鸦上传
        fieldName = self.CONFIG.get('scrawlFieldName')
        config = {
            "pathFormat": self.CONFIG.get('scrawlPathFormat'),
            "maxSize": self.CONFIG.get('scrawlMaxSize'),
            "allowFiles": self.CONFIG.get('scrawlAllowFiles'),
            "oriName": "scrawl.png"
        }
        if fieldName in request.form:
            field = request.form[fieldName]
            uploader = Uploader(field, config, app.static_folder, 'base64')
            return uploader.getFileInfo()
        else:
            return dict(state='上传接口出错')

    def catch_image(self):
        config = {
            "pathFormat": self.CONFIG['catcherPathFormat'],
            "maxSize": self.CONFIG['catcherMaxSize'],
            "allowFiles": self.CONFIG['catcherAllowFiles'],
            "oriName": "remote.png"
        }
        fieldName = self.CONFIG['catcherFieldName']

        if fieldName in request.form:
            # 这里比较奇怪，远程抓图提交的表单名称不是这个
            source = []
        elif '%s[]' % fieldName in request.form:
            # 而是这个
            source = request.form.getlist('%s[]' % fieldName)

        _list = []
        for imgurl in source:
            uploader = Uploader(imgurl, config, app.static_folder, 'remote')
            info = uploader.getFileInfo()
            _list.append({
                'state': info['state'],
                'url': info['url'],
                'original': info['original'],
                'source': imgurl,
            })
        result = dict()
        result['state'] = 'SUCCESS' if len(_list) > 0 else 'ERROR'
        result['list'] = _list
        return result



appbuilder.add_view_no_menu(ZTreeSampleView, "ZTreeSampleView")
